package com.zhouyer.study.server;

import com.zhouyer.study.servlet.HttpServlet;

import java.io.IOException;
import java.net.Socket;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 请求处理线程
 *
 * @author zhouyao
 * @version 1.0
 * @date 2021/9/14 4:27 下午
 */
public class RequestProcessor extends Thread {
    private Socket socket;

    private Mapper mapper;

    public RequestProcessor(Socket socket, Mapper mapper) {
        this.socket = socket;
        this.mapper = mapper;
    }

    private Wrapper getWrapper(Request request) {
        // /demo1/system1/index.html
        String url = request.getUrl();
        if (url.startsWith("/")) {
            // demo1
            String appContext = url.substring(1, url.substring(1).indexOf("/") + 1);
            // /system1/index.html
            String urlPattern = url.substring(url.substring(1).indexOf("/") + 1);
            // 获取对应主机
            Host host = mapper.getHosts().stream().filter(item -> Objects.equals(item.getName(), request.getHost())).findFirst().orElse(null);
            if (null != host) {
                List<Context> contexts = host.getContexts();
                Context context = contexts.stream().filter(item -> Objects.equals(item.getAppContext(), appContext)).findFirst().orElse(null);
                if (null != context) {
                    List<Wrapper> wrapperList = context.getWrapperList();
                    return wrapperList.stream().filter(item -> Objects.equals(item.getUrlPattern(), urlPattern)).findFirst().orElse(null);
                }
            }
        }
        return null;
    }

    @Override
    public void run() {
        try {
            System.out.println("====处理线程：" + Thread.currentThread().getName());
            // 封装Request对象和Response对象
            Request request = new Request(socket.getInputStream());
            Response response = new Response(socket.getOutputStream());
            Wrapper wrapper = getWrapper(request);
            if (null == wrapper) {
                // 处理静态资源
                response.outputHtml(request.getUrl());
            } else {
                // 处理动态资源
                HttpServlet httpServlet = (HttpServlet) wrapper.getServlet();
                httpServlet.service(request, response);
            }
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
